const fs = require('fs');
const path = require('path');

module.exports = function(hexo){
  const base = hexo.base_dir;
  const dest = path.join(base, 'source', 'css', 'custom.css');
  const dataSrc = path.join(base, 'source', '_data', 'styles.styl');

  // 在生成之前尝试删除目标文件，避免之前存在的文件阻止写入
  hexo.extend.filter.register('before_generate', function(){
    try{
      if(fs.existsSync(dest)) fs.unlinkSync(dest);
      hexo.log.info('force-custom-css: removed existing ' + dest);
    }catch(err){
      // 忽略错误
      hexo.log.warn('force-custom-css: failed to remove existing file: ' + err.message);
    }
  });

  // 在生成完成后写入我们希望的 CSS（从 source/_data/styles.styl 读取优先）
  hexo.extend.filter.register('after_generate', function(){
    try{
      let content = '';
      if(fs.existsSync(dataSrc)){
        content = fs.readFileSync(dataSrc, 'utf8');
      } else if(fs.existsSync(dest)){
        content = fs.readFileSync(dest, 'utf8');
      } else {
        // 没有源则用空文件占位
        content = '/* custom.css (generated by scripts/force-custom-css.js) */\n';
      }

      // 确保目录存在
      const dir = path.dirname(dest);
      if(!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

      fs.writeFileSync(dest, content, 'utf8');
      hexo.log.info('force-custom-css: wrote ' + dest);
    }catch(err){
      hexo.log.error('force-custom-css: failed to write file: ' + err.message);
    }
  });
};
